<?php

namespace Recetas\Traits;

use Illuminate\Support\Facades\Lang;

trait UtilTrait {
	
	public function formatDateTranslate(){
		$month = date( 'M', strtotime( $this->created_at ) );
		$formattedDate = date( 'd :M Y', strtotime( $this->created_at ) );
		$localeMonth = Lang::get( 'util.'.$month );
		return str_replace( ':'.$month, $localeMonth, $formattedDate );
	}
	
	public function getTimeElapsed( $full = false ){
		$now = new \DateTime();
		$ago = new \DateTime( $this->created_at );
		$diff = $now->diff( $ago );
	
		$diff->w = floor( $diff->d / 7 );
		$diff->d -= $diff->w * 7;
	
		$translations = array(
				'y' => Lang::choice('util.year', $diff->y ),
				'm' => Lang::choice('util.month', $diff->m ),
				'w' => Lang::choice('util.week', $diff->w ),
				'd' => Lang::choice('util.day', $diff->d ),
				'h' => Lang::choice('util.hour', $diff->h ),
				'i' => Lang::choice('util.minute', $diff->i ),
				's' => Lang::choice('util.second', $diff->s ),
		);
	
		foreach( $translations as $k => &$v ){
			if ( $diff->$k ){
				$v = $diff->$k . ' ' . $v;
			} else {
				unset( $translations[$k] );
			}
		}
	
		if (!$full) $translations = array_slice( $translations, 0, 1);
		return $translations ?
		Lang::get( 'util.timeElapsed', array( 'time' => implode(', ', $translations) ) ) :
		Lang::get( 'util.timeElapsedRightNow' );
	}
	
}